import React, { useState, useRef } from "react";
import styles from "./index.module.less";
import moment from "moment";
// eslint-disable-next-line
import MDEditor from "@uiw/react-md-editor";
import rehypeSanitize from "rehype-sanitize";
import Nav from "@pages/nav";
import PortalContainer from "@components/portalContainer";
import Tag from "@components/tag";
import toast from "@utils/showToast";
import { request } from "@apis/request";
import { useNavigate } from "react-router-dom";

const Publish = () => {
    const navigate = useNavigate();
    const cateRef = useRef(null);

    const [title, setTitle] = useState("");
    const [md, setMd] = useState("");
    const [cate, setCate] = useState("");
    const [cateList, setCateList] = useState([]);
    const [rewardGmoney, setRewardGmoney] = useState("");
    const [isChecked, setIsChecked] = useState(false);

    const publishQuestion = async (e) => {
        e.preventDefault();
        if (e.key === "Enter") return;

        /**验证 */
        if (title.trim().length === 0) {
            toast.fail("标题不能为空");
            return;
        }
        if (md.length === 0) {
            toast.fail("问题缺少markdown描述");
            return;
        }
        if (cateList.length === 0) {
            toast.fail("请用标签词汇为问题分类");
            return;
        }
        if (!isChecked) {
            toast.fail("发布前请确认勾选发布规则");
            return;
        }
        if (
            !rewardGmoney ||
            parseInt(rewardGmoney) !== parseFloat(rewardGmoney) ||
            parseInt(rewardGmoney) <= 0 ||
            isNaN(Number(rewardGmoney))
        ) {
            toast.fail("悬赏G币可以吸引答友前来哦~");
            return;
        }

        const res1 = await request("/api/gmoney");
        if (res1.code === "0000") {
            if (parseInt(rewardGmoney) > res1.data) {
                toast.fail("超出当前G币余额");
                return;
            }
        } else {
            console.log(res1.msg);
            return;
        }

        const res = await request(
            "/questions/publish",
            {
                title,
                mdContent: md,
                cateTags: cateList,
                rewardGmoney: parseInt(rewardGmoney),
            },
            "post"
        );
        console.log("res: ", res);
        if (res.code === "0000") {
            toast.success("发布成功！");
            navigate("/questions", { replace: true });
        } else {
            toast.fail(res.msg);
        }
    };

    const addCateList = (e) => {
        if (e.key === "Enter") {
            if (cateList.length < 3) {
                setCateList([...cateList, cate]);
                setCate("");
                cateRef.current.focus();
            } else {
                toast.fail("分类标签不能超过3个");
                setCate("");
            }
        }
    };

    const deleteCate = (index) => {
        let list = [].concat(cateList);
        list.splice(index, 1);
        setCateList(list);
    };

    return (
        <div className={styles.publish}>
            <Nav />
            <form className={styles.form}>
                <input
                    type="text"
                    name="title"
                    id="title"
                    className={styles.title}
                    required
                    autoComplete="off"
                    placeholder={`请输入标题 ${moment().format(
                        "YYYY年MM月DD日"
                    )}`}
                    maxLength={100}
                    value={title}
                    onChange={(e) => {
                        setTitle(e.target.value);
                    }}
                />
                <p className={styles.attention}>
                    <span>*注意：</span>
                    问题描述不详、需求不清晰、内容违规等，可能导致问题被删除！
                </p>
                <MDEditor
                    height={document.body.clientWidth > 1550 ? 400 : 320}
                    value={md}
                    onChange={setMd}
                    previewOptions={{
                        rehypePlugins: [[rehypeSanitize]],
                    }}
                    visibleDragbar={false}
                />
                <label htmlFor="categaryTag" className={styles.cate_tag}>
                    <span>问题分类：</span>
                    <input
                        type="text"
                        id="categaryTag"
                        name="categaryTag"
                        className={styles.categaryTag}
                        placeholder="如html, css, js, React, Vue..."
                        autoComplete="off"
                        ref={cateRef}
                        value={cate}
                        onChange={(e) => {
                            setCate(e.target.value);
                        }}
                        onKeyUp={(e) => {
                            addCateList(e);
                        }}
                    />
                    <span className={styles.small_tip}>
                        输入一个分类词汇后，可按回车显示分类标签
                    </span>
                </label>
                <div className={styles.cate_list}>
                    <ul className={styles.cate_list_ul}>
                        {cateList &&
                            cateList.map((item, index) => {
                                return (
                                    <li
                                        key={index}
                                        onClick={() => {
                                            deleteCate(index);
                                        }}
                                    >
                                        <Tag tag={item} />
                                    </li>
                                );
                            })}
                    </ul>
                </div>
                <label htmlFor="rewardGmoney">
                    悬赏G币：&emsp;
                    <input
                        type="number"
                        name="rewardGmoney"
                        id="rewardGmoney"
                        required
                        className={styles.rewardGmoney}
                        placeholder={0}
                        value={rewardGmoney}
                        onChange={(e) => {
                            setRewardGmoney(e.target.value);
                        }}
                    />
                </label>
                <br />
                <label htmlFor="confirmRight" className={styles.confirmRight}>
                    <input
                        type="checkbox"
                        name="confirmRight"
                        id="confirmRight"
                        required
                        checked={isChecked}
                        onChange={(e) => {
                            setIsChecked(e.target.checked);
                        }}
                    />
                    &nbsp;
                    <span>
                        我已努力尝试解决，并将问题描述清楚完整，表达了个人需求，且遵守法律法规。
                    </span>
                </label>
                <br />
                <input
                    type="button"
                    value="发布"
                    className={styles.publish_btn}
                    onClick={(e) => {
                        publishQuestion(e);
                    }}
                />
            </form>
            <PortalContainer />
        </div>
    );
};

export default Publish;
